package register

import (
	"crypto/md5"
	"database/sql"
	"errors"
	"fmt"
)

// User have the verify method
type User interface {
	Verify(pq *sql.DB) (bool, error)
}

// StandarUser provide the standar user
type StandarUser struct {
	ID       int    `json:"id"`
	Name     string `json:"name"`
	Password string `json:"password"`
	Rolename string `json:"rolename"`
}

// Verify use the standar user
func (s *StandarUser) Verify(pq *sql.DB) (bool, error) {
	if s.ID == 0 {
		return false, errors.New("self:id required")
	}
	var pass string
	err := pq.QueryRow(`SELECT name,password FROM user WHERE id=$1`, s.ID).Scan(&s.Name, &pass)
	if err != nil {
		return false, err
	}

	hash := md5.New()
	hash.Write([]byte(s.Password))
	hashCode := fmt.Sprintf("%x", hash.Sum(nil))
	if hashCode == pass {
		return true, nil
	}

	return false, errors.New("self:password is not match")

}
